import os
import random
import time
import cv2 as cv

from . import b_inter
import numpy as np
from YD_C.COM import globals
from YD_C.COM.common import *
# add_etched_circle, rand_center, create_img_random, add_salt_noise, add_guassianBlur, \
#     calculate_single_circle_centerpoint, add_salt_noise_ring, make_spots_image, create_img_by_img, add_median_filter


class inter_Imp(b_inter.yoloDataC):
    def __init__(self, base_save, numimg):
        super().__init__(base_save, numimg)
        self.num_img = numimg
        self.base_save_path = base_save


    def generate_image(self, bmp_type=None):
        # str(bmp_type) + str(i)
        for i in range(0, self.num_img + 1):
            timestamp = time.time()
            time_struct = time.localtime(timestamp)
            # 修改时间格式，将冒号替换为合法字符
            formatted_time = time.strftime('%Y-%m-%d-%H-%M-%S', time_struct)  # 原格式有冒号
            
            self.bmp_save_path = os.path.join(self.base_save, str(formatted_time)+ '.bmp')
            label_save = os.path.join(self.base_save, "res")
            if not os.path.exists(label_save):
                os.makedirs(label_save)
            # 文件名中的冒号已替换为连字符
            self.label_save_path = os.path.join(label_save, f"{formatted_time}.txt")
            self.label_save_path = open(self.label_save_path, "w")
            cases = {
                "circle": self.circle,
                "ring": self.ring,
                "rwc": self.ringWithCircle,
                "cm": self.circleMatrix,
                "crm": self.circleRingMatrix,
                "holes": self.holes,
                "spots": self.spots
            }
            cases.get(bmp_type, self.default)()
            if i % 10 == 0:
                print(i)

    # 圆
    def circle(self):
        radius = random.randint(30, 150)  # 随机的圆的直径在 60 - 400 之间c
        diameter = 2 * radius
        center = rand_center(radius)
        # 判定当前圆形绘制的颜色为黑色还是白色
        circle_color = 60 if np.random.rand() < 0.5 else 230
        rect_color = 0 if circle_color == 230 else 255

        blank_circle = create_img_random() #if np.random.rand() < 0.5 else create_img_by_img("C:/Users/1234/Desktop/img_test/1.bmp")
        cv.circle(blank_circle, center, radius, circle_color, -1, cv.LINE_AA)
        # 根据yolov7训练要求，计算中心坐标与图片宽高的比例， 直径在宽高方向上的比例
        center_x = center[0] / globals.height
        center_y = center[1] / globals.width
        dx = diameter / globals.height
        dy = diameter / globals.width
        self.label_save_path.write(
            "0" + ' ' + str(center_x) + ' ' + str(center_y) + ' ' + str(dx) + ' ' + str(dy) + ' ')
        xmin = center[0] - radius
        ymin = center[1] - radius
        xmax = center[0] + radius
        ymax = center[1] + radius
        box = globals.bbox(xmin, ymin, xmax, ymax)
        # cv.rectangle(blank_circle, (xmin, ymin), (xmax, ymax), rect_color, 1)
        # 在绘制圆形的区域添加椒盐噪点
        salt_noise = 0.6
        add_salt_noise(blank_circle, box, center, radius, salt_noise)
        blurred = add_guassianBlur(blank_circle)
        if np.random.rand() < 0.5:
            blurred = add_etched_circle(blurred, center, radius)
        cv.imwrite(self.bmp_save_path, blurred)

    # 圆环
    def ring(self):
        # image = create_img_by_img("C:/Users/1234/Desktop/yolotestdata/markyangben/ring/3.0/A/1.bmp"
        image = create_img_random()
        color = 255
        img_ = 255 * np.zeros((globals.width, globals.height), dtype=np.uint8)
        img_2 = 255 * np.zeros((globals.width, globals.height), dtype=np.uint8)
        img_[:] = color
        img_2[:] = color
        max_radius = random.randint(145, 200)
        min_radius = max_radius - random.randint(20, 40)
        x = random.randint(max_radius, globals.width - 2 * max_radius)
        y = random.randint(max_radius, globals.height - 2 * max_radius)
        center = (y, x)
        xmin = center[0] - max_radius
        ymin = center[1] - max_radius
        xmax = center[0] + max_radius
        ymax = center[1] + max_radius
        box = globals.bbox(xmin, ymin, xmax, ymax)
        # 圆环内圆   RING  innercircle
        center_x = center[0] / globals.height
        center_y = center[1] / globals.width
        dx = (2 * min_radius) / globals.height
        dy = (2 * min_radius) / globals.width
        # 圆环外圆   RING  outercircle
        dx2 = (2 * max_radius) / globals.height
        dy2 = (2 * max_radius) / globals.width
        self.label_save_path.write(
            "0" + ' ' + str(center_x) + ' ' + str(center_y) + ' ' + str(dx) + ' ' + str(dy) + ' ' + '\n')
        self.label_save_path.write(
            "1" + ' ' + str(center_x) + ' ' + str(center_y) + ' ' + str(dx2) + ' ' + str(dy2) + ' ' + '\n')
        blackColor = random.randint(0, 100)
        cv.circle(img_, center, max_radius, blackColor, 0, cv.LINE_AA)
        cv.circle(img_2, center, min_radius, blackColor, 0, cv.LINE_AA)
        difference = cv.absdiff(img_, img_2)
        _, threshold = cv.threshold(difference, 20, 255, cv.THRESH_BINARY)
        noise_size = 0.5
        resImage = cv.add(threshold, image)
        add_salt_noise_ring(resImage, box, center, max_radius, min_radius, noise_size)
        blurred = add_guassianBlur(resImage)
        cv.imwrite(self.bmp_save_path, blurred)
        

    # 圆环+圆
    def ringWithCircle(self):
        image = create_img_by_img("C:/Users/1234/Desktop/yolotestdata/markyangben/circle+ring/FHBW/1.bmp")
        color = 255
        img_ = 255 * np.zeros((globals.width, globals.height), dtype=np.uint8)
        img_2 = 255 * np.zeros((globals.width, globals.height), dtype=np.uint8)
        img_[:] = color
        img_2[:] = color
        max_radius = random.randint(150, 200)
        min_radius = max_radius - random.randint(20, 30)
        inner_circle_radius = min_radius - random.randint(50, 70)
        x = random.randint(max_radius, globals.width - 2 * max_radius)
        y = random.randint(max_radius, globals.height - 2 * max_radius)
        center = (y, x)
        xmin = center[0] - max_radius
        ymin = center[1] - max_radius
        xmax = center[0] + max_radius
        ymax = center[1] + max_radius
        # cv.rectangle(img_, (xmin, ymin), (xmax, ymax), (0, 255, 0), 1)
        # cv.rectangle(img_, (center[0] - min_radius, center[1] - min_radius),
        #              (center[0] + min_radius, center[1] + min_radius), (0, 0, 0), 1)
        # cv.rectangle(img_, (center[0] - inner_circle_radius, center[1] - inner_circle_radius),
        #              (center[0] + inner_circle_radius, center[1] + inner_circle_radius), (0, 0, 255), 1)

        box = globals.bbox(xmin, ymin, xmax, ymax)
        # 圆环内圆   RING  innercircle
        center_x = center[0] / globals.height
        center_y = center[1] / globals.width
        dx = (2 * min_radius) / globals.height
        dy = (2 * min_radius) / globals.width
        # 圆环外圆   RING  outercircle
        dx2 = (2 * max_radius) / globals.height
        dy2 = (2 * max_radius) / globals.width
        # 圆+圆环中的圆   circle
        dx3 = (2 * inner_circle_radius) / globals.height
        dy3 = (2 * inner_circle_radius) / globals.width
        self.label_save_path.write(
            "0" + ' ' + str(center_x) + ' ' + str(center_y) + ' ' + str(dx3) + ' ' + str(dy3) + ' ' + '\n')
        self.label_save_path.write(
            "1" + ' ' + str(center_x) + ' ' + str(center_y) + ' ' + str(dx2) + ' ' + str(dy2) + ' ' + '\n')
        self.label_save_path.write(
            "2" + ' ' + str(center_x) + ' ' + str(center_y) + ' ' + str(dx) + ' ' + str(dy) + ' ' + '\n')

        blackColor = random.randint(0, 100)
        cv.circle(img_, center, max_radius, blackColor, 0, cv.LINE_AA)
        cv.circle(img_2, center, min_radius, blackColor, 0, cv.LINE_AA)
        difference = cv.absdiff(img_, img_2)
        _, threshold = cv.threshold(difference, 20, 255, cv.THRESH_BINARY)
        noise_size = 0.8
        resImage = cv.add(threshold, image)
        add_salt_noise_ring(resImage, box, center, max_radius, min_radius, noise_size)

        inner_circle_color = random.randint(30, 50)
        cv.circle(resImage, center, inner_circle_radius, inner_circle_color, -1, cv.LINE_AA)
        xminc = center[0] - inner_circle_radius
        yminc = center[1] - inner_circle_radius
        xmaxc = center[0] + inner_circle_radius
        ymaxc = center[1] + inner_circle_radius
        circle_box = globals.bbox(xminc, yminc, xmaxc, ymaxc)
        noise_sizez = 0.6
        add_salt_noise(resImage, circle_box, center, inner_circle_radius, noise_sizez)
        blurred = add_guassianBlur(resImage)
        cv.imwrite(self.bmp_save_path, blurred)

    # 圆阵
    def circleMatrix(self):
        # C:\Users\1234\Desktop\yolotestdata\markyangben\circlemartrix\juzhenkong
        rand_img = create_img_by_img("C:/Users/1234/Desktop/yolotestdata/markyangben/circlemartrix/juzhenkong/7.5.bmp")
        radius = random.randint(7, 15)
        dx = (2 * radius) / globals.height
        dy = (2 * radius) / globals.width
        center0 = (random.randint(100, 200), random.randint(100, 200))
        color = random.randint(200, 235)
        # color = 235
        offset = 2 * radius + random.randint(50, 100)
        # offsetY = random.randint(50, 100)
        num_list = 6
        for i in range(1, num_list):
            for j in range(1, num_list):
                center = (center0[0] + i * offset, center0[1] + j * offset)
                centerx = center[0] / globals.height
                centery = center[1] / globals.width
                self.label_save_path.write(
                    "4" + ' ' + str(centerx) + ' ' + str(centery) + ' ' + str(dx) + ' ' + str(dy) + ' ' + '\n')
                cv.circle(rand_img, center, radius, color, -1, cv.LINE_AA)
        ksize = (3, 3)
        sigma = 0
        blurred = cv.GaussianBlur(rand_img, ksize, sigma)
        cv.imwrite(self.bmp_save_path, blurred)

    # 圆环阵
    def circleRingMatrix(self):
        center_circle_radius = random.randint(75, 120)
        single_circle_radius = random.randint(18, 25)
        center_circle_point = rand_center(center_circle_radius)
        sc_cp = calculate_single_circle_centerpoint(center_circle_point, center_circle_radius, single_circle_radius)
        color = random.randint(30, 40)
        blank_circle = create_img_by_img("C:/Users/1234/Desktop/yolotestdata/23.05.26/circlesring/1.bmp")
        for iss in range(len(sc_cp)):
            index = iss % len(sc_cp)
            single = sc_cp[index]
            # 一下是yolov7训练数据
            centerx = (single[0]) / globals.height
            centery = (single[1]) / globals.width
            dx = (2 * single_circle_radius) / globals.height
            dy = (2 * single_circle_radius) / globals.width
            self.label_save_path.write(
                "0" + ' ' + str(centerx) + ' ' + str(centery) + ' ' + str(dx) + ' ' + str(dy) + ' ' + "\n")
            cv.circle(blank_circle, (int(single[0]), int(single[1])), single_circle_radius, color, -1, cv.LINE_AA)

            xmin = int(single[0] - single_circle_radius)
            ymin = int(single[1] - single_circle_radius)
            xmax = int(single[0] + single_circle_radius)
            ymax = int(single[1] + single_circle_radius)
            box = globals.bbox(xmin, ymin, xmax, ymax)
            # cv.rectangle(blank_circle, (xmin, ymin), (xmax, ymax), 255, 5)
            # 在绘制圆形的区域添加椒盐噪点
            salt_noise = 0.3
            add_salt_noise(blank_circle, box, single, single_circle_radius, salt_noise)
            blurred = add_guassianBlur(blank_circle)
            media_blurred = add_median_filter(blurred)
            cv.imwrite(self.bmp_save_path, media_blurred)

    # 孔，洞
    def holes(self):
        pass

    # 噪点，污渍
    def spots(self, box):
        self.spotsBox = box
        image = create_img_random()
        # 在规定box范围内进行随机生成噪点，颜色偏深，图形不规则
        for i in range(0, len(self.spotsBox)):
            spotbox = self.spotsBox[i]
            make_spots_image(image, spotbox)
        cv.imshow("11", image)
        cv.waitKey(0)

    # cases默认情况下执行的方法
    def default(self):
        print("Nothing Bmp_type Created!")
